package com.yorick.file.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yorick.common.Result.SimpleFactory.ResultFactory;
import com.yorick.common.error.YorickAssert;
import com.yorick.file.dao.FileMapper;
import com.yorick.file.entity.AccountFileDto;
import com.yorick.file.entity.DeleteFileDto;
import com.yorick.file.entity.FileDto;
import com.yorick.file.entity.Node;
import com.yorick.file.modal.response.FileDetailResponse;
import com.yorick.file.service.BinService;
import com.yorick.file.util.TreeRecursion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class BinServiceImpl extends TreeRecursion implements BinService {
    @Autowired
    FileMapper fileMapper;
    @Resource
    protected ObjectMapper objectMapper;

    @Override
    public Map<String, Object> fileList(int aid) {
        List<JSONObject> result = new ArrayList<>();
        List<FileDto> fileList = fileMapper.getDisabledFileList(aid);
        if (fileList.size() > 0) {
            result = formatTreeRecursionData(fileList);
        }
        return ResultFactory.success(result).display();
    }

    @Override
    public Map<String, Object> deleteFile(int fileId, int aid) {
        AccountFileDto data = AccountFileDto.builder()
                .aid(aid)
                .fileId(fileId)
                .build();
        Integer isExist = fileMapper.isDelFileExist(data);
        YorickAssert.validate(
                isExist > 0,
                () -> "0",
                () -> "你没有权限删除该文件");

        FileDto data2 = FileDto.builder()
                .aid(aid)
                .id(fileId)
                .build();
        List<Integer> childList = fileMapper.findFileChildList(data2);
        DeleteFileDto data3 = DeleteFileDto.builder()
                .aid(aid)
                .fileIds(childList)
                .build();
        fileMapper.deleteFile(data3);
        fileMapper.deleteAccountFile(data3);
        return ResultFactory.success().display();
    }

    @Override
    public Map<String, Object> restoreFile(int fileId, int aid) {
        FileDto data = FileDto.builder()
                .aid(aid)
                .id(fileId)
                .build();

        List<Integer> childList = fileMapper.findFileChildList(data);
        List<Integer> parentList = fileMapper.findFileParentList(data);
        parentList.parallelStream().forEach(parentId ->{
            FileDto parentData = FileDto.builder()
                    .aid(aid)
                    .id(parentId)
                    .build();
            FileDto parentFile = fileMapper.findFileById(parentData);
            FileDto parentData2 = FileDto.builder()
                    .fileName(parentFile.getFileName())
                    .parentId(parentFile.getParentId())
                    .build();
            Integer isExist = fileMapper.isFileExist(parentData2);
            if (isExist>0){
                Integer existFileId = fileMapper.existFileId(parentData2);
                if(existFileId.intValue()!=parentFile.getId().intValue()){
                    YorickAssert.validate(
                            isExist == 0,
                            () -> "0",
                            () -> "该文件夹或文件已存在，无法还原");
                }
            }
        });
        List<Integer> joined = new ArrayList<Integer>();
        joined.addAll(childList);
        joined.addAll(parentList);
        DeleteFileDto data3 = DeleteFileDto.builder()
                .aid(aid)
                .fileIds(joined)
                .enabled(1)
                .build();
        fileMapper.updateFileStatus(data3);
        fileMapper.updateFileLastTime(data3);
        return ResultFactory.success().display();
    }

    private List<JSONObject> formatTreeRecursionData(List<FileDto> fileList){
        int nodeId = fileList.get(0).getParentId();
        Map<Integer, Node> nodes = new HashMap<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileDto fileDto = fileList.get(i);
            //模拟数据库存储树结构
            Node node = Node.builder()
                    .id(fileDto.getId())
                    .parentId(fileDto.getParentId())
                    .fileName(fileDto.getFileName())
                    .fileType(fileDto.getFileType())
                    .fileSize(fileDto.getFileSize())
                    .lastTime(fileDto.getLastTime())
                    .isPrivate(fileDto.getIsPrivate())
                    .build();
            nodes.put(fileDto.getId(), node);
        }
        return getNodeJson(nodes);
    }

    @Override
    protected JSONObject customizeNode(Node node) {
        FileDetailResponse childResponse = FileDetailResponse.builder()
                .id(node.getId())
                .parentId(node.getParentId())
                .fileName(node.getFileName())
                .fileType(node.getFileType())
                .fileSize(node.getFileSize())
                .lastTime(node.getLastTime())
                .isPrivate(node.getIsPrivate())
                .build();
        return objectMapper.convertValue(childResponse, JSONObject.class);
    }

}
